<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-box">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="账户">
          <el-input v-model="searchForm.adminId" placeholder="请输入账户" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="权限等级">
          <el-select
            v-model="searchForm.permission"
            placeholder="选择权限等级"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="(name, value) in roleMap"
              :key="value"Text
              :label="name"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.adminText" placeholder="请输入关键词" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="mb-4">
      <el-button type="primary" @click="handleAdd">
        +添加用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="showUsers"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="adminId" label="账户" width="180" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="permission" label="权限" width="120">
        <template #default="{row}">
          <el-tag :type="roleTagType[row.permission]">
            {{ roleMap[row.permission] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="default" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="default"
            type="danger"
            @click="handleDelete(row.adminId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showDialog"
      width="600px"
    >
      <el-form
        ref="userForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="账户" prop="adminId">
          <el-input
            v-model="formData.adminId"
            :disabled="!isAdd"
            placeholder="请输入账户"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="passwd" :required="isAdd">
          <el-input
            v-model="formData.passwd"
            type="password"
            show-password
            :placeholder="isAdd ? '请输入密码' : '留空不修改'"
          />
        </el-form-item>
        <el-form-item label="权限等级" prop="permission">
          <el-select
            v-model="formData.permission"
            placeholder="请选择权限"
            style="width: 100%"
          >
            <el-option
              v-for="(name, value) in roleMap"
              :key="value"Text
              :label="name"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户信息" prop="adminText">
          <el-input
            v-model="formData.adminText"
            type="textarea"
            :rows="3"
            placeholder="请输入用户信息"
          />
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteUser, addUser, updateUser, getAllUser } from '@/api/Login'

// 权限配置
const roleMap = {
  3: '原始管理员',
  2: '超级管理员',
  1: '普通管理员'
}

const roleTagType = {
  3: 'danger',
  2: 'warning',
  1: 'success'
}

// 用户数据
const showUsers = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  adminId: null,
  name: null,
  permission: null,
  adminText: null
})

// 表单验证规则
const rules = reactive({
  adminId: [
    { required: true, message: '账户不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  passwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  permission: [
    { required: true, message: '请选择权限等级', trigger: 'change' }
  ]
})

// 弹窗相关状态
const showDialog = ref()
const isAdd = ref(false)
const userForm = ref(null)
const formData = ref({
  adminId: '',
  name: '',
  passwd: '',
  permission: 1,
  adminText: ''
})

// 计算属性
const dialogTitle = computed(() => isAdd.value ? '添加用户' : '编辑用户')

// 获取用户列表
function updateShowUsers() {
  loading.value = true
  getAllUser(searchForm.value).then(res => {
    showUsers.value = res.data.data || []
    loading.value = false
  })
}


// 搜索
function handleSearch() {
  updateShowUsers()
}

// 重置搜索
function resetSearch() {
  searchForm.value = {
    adminId: null,
    name: null,
    permission: null, 
    adminText: null
  }
  updateShowUsers()
}

// 删除用户
async function handleDelete(id) {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${id} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteUser(id)
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      updateShowUsers()
    }
    else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 添加用户
function handleAdd() {
  isAdd.value = true
  showDialog.value = true
  formData.value = {
    adminId: '',
    name: '',
    passwd: '',
    permission: 1,  
    adminText: ''
  }
}

// 编辑用户
function handleEdit(user) {
  formData.value = {...user}
  showDialog.value = true
  isAdd.value = false
}

// 提交表单
function submitForm() {
  if(isAdd.value){
    addUser(formData.value).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('添加成功')
        showDialog.value = false
        updateShowUsers()
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  }else{
    updateUser(formData.value).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('修改成功')
        showDialog.value = false
        updateShowUsers()
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  }
}
// 初始化加载数据
updateShowUsers()
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}
</style>
